package com.app.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.app.dao.UserDao;
import com.app.entity.User;
import com.app.service.UserService;

@Service
@Transactional(readOnly=true)
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	
	@Override
	public User findUserByParameter(User user) {
		return userDao.findUserByParameter(user);
	}

	@Transactional(readOnly=false)
	public boolean updatePassword(User user, String newPassword) {
		Assert.notNull(newPassword);
		user = userDao.findUserByParameter(user);
		if (user.getId() != null) {
			Md5PasswordEncoder md5 = new Md5PasswordEncoder();
			newPassword = md5.encodePassword(newPassword, user.getName());
			user.setPassword(newPassword);
			userDao.updatePassword(user);
			
			return true;
		}
		return false;
	}

	@Override
	public boolean login(User user) {
		if(userDao.findUserByParameter(user).getId() != null)
			return true;
		
		return false;
	}

}
